package org.zoomdev.zoom.lock.modules;


import org.zoomdev.zoom.lock.KeyedObjectPool;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

class ProxyLock implements Lock {

    private final Lock lock;
    private final KeyedObjectPool<Lock> pool;
    private String key;

    public ProxyLock(KeyedObjectPool<Lock> pool) {
        this(pool, false);
    }

    public ProxyLock(KeyedObjectPool<Lock> pool, boolean fair) {
        this.pool = pool;
        this.lock = new ReentrantLock(fair);
    }

    public void setKey(String key) {
        this.key = key;
    }

    @Override
    public void lock() {
        lock.lock();
    }

    @Override
    public void lockInterruptibly() throws InterruptedException {
        lock.lockInterruptibly();
    }

    @Override
    public boolean tryLock() {
        return lock.tryLock();
    }

    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return lock.tryLock(time, unit);
    }

    @Override
    public void unlock() {
        try {
            pool.release(key, this);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public Condition newCondition() {
        return lock.newCondition();
    }
}